package dtu.k12tpm.pbs.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;
import dtu.k12tpm.pbs.service.GMailSender;
import dtu.k12tpm.pbs.service.WebService;
import dtu.k12tpm.pbs.util.EmailParser;

public class LoginActivity extends MyActivity {

	/** Called when the activity is first created. */
	public static String		US;
	public static String		PW;
	public static int			USERID;
	public CheckBox check;
	private static final String	STRING_NAME_USERSETTING	= "USER REFERENCES";
	private SharedPreferences	mShareRefs				= null;
	Handler						myHandler				= new Handler();

	public static int getUserID() {
		return USERID;
	}

	public static void setUsername(String username) {
		US = username;
	}

	public static void setPassword(String password) {
		PW = password;
	}

	public static String getUsername() {
		return US;
	}

	public static String getPassword() {
		return PW;
	}

	public void ExitClick(View v) {
		try {
			saveSetting("username", "");
			saveSetting("password", "");
			finalize();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		this.finish();
	}

	public void saveSetting(String key, String value) {
		mShareRefs = getSharedPreferences(STRING_NAME_USERSETTING, Activity.MODE_PRIVATE);
		Editor editor = mShareRefs.edit();
		if (value.trim().equals("")) {
			editor.clear();
		} else {
			editor.putString(key, value);
		}
		editor.commit();
	}

	public String getSetting(String key) {
		mShareRefs = getSharedPreferences(STRING_NAME_USERSETTING, Activity.MODE_PRIVATE);
		return mShareRefs.getString(key, "");
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_PROGRESS);
		setTitle("Login PBSM");
		setContentView(R.layout.login_screen);
		check = (CheckBox)findViewById(R.id.CheckBox01);
		check.setChecked(true);
		String pass = getSetting("password");
		String username = getSetting("username");
//		if(!pass.equals("") && !username.equals("")){
//			try {
//				String msg = WebService.checkLogin(username, pass);
//				USERID = Integer.parseInt(msg.trim());
//				if( USERID != -1 ){
//					Intent intent = new Intent(LoginActivity.this, MainContactListActivity.class);
//					startActivity(intent);
//				}
//				
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
	}

	public void ForgotAccount(View v) {
		LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View content = vi.inflate(R.layout.restore_account, null);		
		final EditText inputBoxEmail = (EditText)content.findViewById(R.id.txtEmail);

		new AlertDialog.Builder(this).setView(content).setTitle("Recover Account").setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d, int which) {
				final String email = inputBoxEmail.getText().toString();
				if (new EmailParser(email).isValid()) {
					final ProgressDialog pd = showProgressDialog("Account is sending to your email...", false);
					new Thread() {
						public void run() {
							try {
								String result = WebService.getAccountConnectedToEmail(email);
								if (result.equals("")) {
									myHandler.post(new Runnable() {
										@Override
										public void run() {
											showMessageDialog(null, "We cannot found any usernames connected with your email \"" + email + "\"");
										}
									});
								} else {
									GMailSender sender = new GMailSender(getString(R.string.mail_username), getString(R.string.mail_password));
									sender.sendMail("Support recover username from phonebooksafe", "Your username: " + result, "account-recovery-noreply", email);
									myHandler.post(new Runnable() {
										@Override
										public void run() {
											showMessageDialog(null, "Your account sent to \"" + email + "\"");
										}
									});
								}
								myHandler.post(new Runnable() {
									@Override
									public void run() {
										pd.dismiss();
									}
								});

							} catch (final Exception e) {
								myHandler.post(new Runnable() {
									@Override
									public void run() {
										pd.dismiss();
										showMessageDialog("Error Connect", e.getMessage() + "\nPlease try again");
									}
								});
							}
						}
					}.start();
				} else {
					showToast(R.string.msg_EmailInvalid);
				}
			}
		}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d, int which) {
				d.dismiss();
			}
		}).create().show();
	}

	public boolean checkAccountInfo(String user, String pass, String cofirmPass, String email) {
		if (user == null || user.equals("")) {
			showToast(R.string.msg_MissUsername);
			return false;
		}
		if (pass == null || pass.equals("")) {
			showToast(R.string.msg_MissPassword);
			return false;
		}
		if (cofirmPass == null || cofirmPass.equals("") || !pass.equals(cofirmPass)) {
			showToast(R.string.msg_WrongConfirmPassword);
			return false;
		}
		if (email == null || email.equals("")) {
			showToast(R.string.msg_MissEmail);
			return false;
		}
		if (!new EmailParser(email).isValid()) {
			showToast(R.string.msg_EmailInvalid);
			return false;
		}
		return true;
	}

	public void CreateAccountButtonClick(View v) {
		LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View content = vi.inflate(R.layout.singup, null);
		final EditText inputBoxUsername = (EditText)content.findViewById(R.id.txtUsername);
		final EditText inputBoxPassword = (EditText)content.findViewById(R.id.txtPassword);
		final EditText inputBoxConfirmPassword = (EditText)content.findViewById(R.id.txtConfirmPassword);
		final EditText inputBoxEmail = (EditText)content.findViewById(R.id.txtEmail);

		new AlertDialog.Builder(this).setView(content).setTitle("Create New Account").setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d, int which) {
				final String username = inputBoxUsername.getText().toString();
				final String password = inputBoxPassword.getText().toString();
				final String confirm_password = inputBoxConfirmPassword.getText().toString();
				final String email = inputBoxEmail.getText().toString();
				if (checkAccountInfo(username, password, confirm_password, email)) {
					final ProgressDialog pd = showProgressDialog("Please waiting...", false);
					new Thread(){
						public void run(){
							try {						
								final String msg = WebService.createAccount(username, password, email);
								myHandler.post(new Runnable() {									
									@Override
									public void run() {
										pd.dismiss();
										showToast(msg);
									}
								});								
							} catch (Exception e) {
								myHandler.post(new Runnable() {									
									@Override
									public void run() {
										pd.dismiss();
										showErrorDialog("Error when attempting connect to server");
									}
								});								
							}
						}
					}.start();					
				}
			}
		}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d, int which) {
				d.dismiss();
			}
		}).create().show();
	}

	public void LoginButtonClick(View v) {
		final ProgressDialog pd = showProgressDialog("Login", "Please wait...", R.drawable.lock, false);
		final Thread threadLogin = new Thread() {
			public void run() {
				try {

					final String username = ((EditText) findViewById(R.id.txtUsername)).getText().toString();
					final String password = ((EditText) findViewById(R.id.txtPassword)).getText().toString();
					if (username.equals("") || password.equals("")) {
						myHandler.post(new Runnable() {
							@Override
							public void run() {
								pd.dismiss();
								showToast("Please enter your account");
							}
						});
					} else {
						String msg = WebService.checkLogin(username, password);
						USERID = Integer.parseInt(msg.trim());
						if (USERID == -1) {
							myHandler.post(new Runnable() {
								@Override
								public void run() {
									pd.dismiss();
									showToast("Wrong username or password");
								}
							});
						} else {
							US = username;
							PW = password;
//							File file = new File("/"+username);
//							file.mkdirs();
							final boolean chk = ((CheckBox) LoginActivity.this.findViewById(R.id.CheckBox01)).isChecked();
							myHandler.post(new Runnable() {
								@Override
								public void run() {
									if (chk) {
										LoginActivity.this.saveSetting("password", password);
										LoginActivity.this.saveSetting("username", username);
									} else {
										LoginActivity.this.saveSetting("password", "");
										LoginActivity.this.saveSetting("username", "");
									}
									Intent intent = new Intent(LoginActivity.this, MainContactListActivity.class);
									startActivity(intent);
									pd.dismiss();
								}
							});
						}
					}

				} catch (final Exception e) {
					myHandler.post(new Runnable() {
						@Override
						public void run() {
							pd.dismiss();
							showMessageDialog("Error Connect", e.getMessage() + "\nPlease try again");
						}						
					});
					
				}
			}
		};
		threadLogin.start();
	}
	
}